﻿using System;
using System.Collections.Generic;
using SimpleOrmCFPC.Core.RequestsComputer.Dialects;
using SimpleOrmCFPC.Helpers;
using SimpleOrmCFPC.Core.Model;

namespace SimpleOrmCFPC.Core.RequestsComputer
{
    public static class TypeConverter
    {
        public static DbType ToDbType(this Type type)
        {
            var mappings = new Dictionary<Type, DbType>
                {
                    {typeof (string), DbType.Char},
                    {typeof (int), DbType.Integer},
                    {typeof (bool), DbType.Integer},
                    {typeof (byte), DbType.Integer},
                    {typeof (sbyte), DbType.Integer},
                    {typeof (UInt16), DbType.Integer},
                    {typeof (Int16), DbType.Integer},
                    {typeof (UInt32), DbType.Bigint},
                    {typeof (Int64), DbType.Bigint},
                    {typeof (UInt64), DbType.Bigint},
                    {typeof (DateTime), DbType.Date},
                    {typeof (decimal), DbType.Float},
                    {typeof (float), DbType.Float},
                    {typeof (double), DbType.Float},
                    {typeof (byte[]), DbType.Blob}
                };

            if (type.IsEnum)
                return DbType.Integer;
            if (type.IsEntity())
                return ToDbType(type.GetPrimaryKey().PropertyType);
            if (!mappings.ContainsKey(type))
                throw new UnsupportedTypeException(type);
            return mappings[type];
        }
    }
}